package com.yonyou.ucf.mdf.app.isvdxq.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.yonyou.ucf.mdf.app.isvdxq.common.DxqConfig;
import com.yonyou.ucf.mdf.app.isvdxq.common.NoNeedToken;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.TenantConfig;
import com.yonyou.ucf.mdf.app.isvdxq.other.service.BaseService;
import com.yonyou.ucf.mdf.app.isvdxq.other.service.MyTokenService;
import com.yonyou.ucf.mdf.app.isvdxq.utils.MyTool;
import com.yonyou.ucf.mdf.app.isvdxq.utils.RequestTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Slf4j
@Component
public class DXQHeaderInterceptor extends HandlerInterceptorAdapter {
    private static final Logger logger = LoggerFactory.getLogger(DXQHeaderInterceptor.class);
    @Autowired
    private BaseService baseService;

    @Autowired
    private MyTokenService myTokenService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            System.out.println("[HeaderInterceptor][GDGY]" + request.getRequestURI());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            //YhtToken放行
            String yht_access_token = baseService.getYhtAccessToken(request);
            //默认接收 tenantId赋值
            String tenantId_Now = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            //获取Token
            String access_token = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_ACCESS_TOKEN);

            //获取上下文信息
//            if (StringUtils.isNotBlank(yht_access_token)){
//                myTokenService.buildContextByYhtAccessToken(yht_access_token);
//            }
            if (StringUtils.isEmpty(tenantId_Now)) {
                tenantId_Now = myTokenService.getTenantId();
            } else if (StringUtils.isEmpty(userId)) {
                userId = myTokenService.getYhtUserid();
            }
            // 对于注解的判断---------------------------------------------------
            if (!(handler instanceof HandlerMethod)) {
                return true;
            }
            // 用友在线平台放行
            boolean yhtAccessTokenValid = myTokenService.isYhtAccessTokenValid(yht_access_token);
            if (yhtAccessTokenValid) {
                return true;
            }

            PrintWriter out;
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            if (handlerMethod.getMethodAnnotation(NoNeedToken.class) != null || handlerMethod.getBeanType().isAnnotationPresent(NoNeedToken.class)) {
                // 如果自己拥有NoNeedToken标注或者所属的class拥有NoNeedToken 就直接放行
                return true;
            }

            /** 本地租户缓存列表
             * 获取租户配置 目前考虑是单独部署 或者 不是的话，appKey 不影响业务逻辑token获取
             * suite 租户方案，是否每个租户单独自动化部署？关注appKey，tenantId accessToken 等信息
             */
            TenantConfig tenantConfig = baseService.GetTenantConfig(request);
            baseService.TenantConfigInit(tenantConfig, userId);

            if (StringUtils.isNotEmpty(tenantId_Now) && StringUtils.isNotEmpty(userId)) {
                baseService.AppconfigInit(tenantId_Now, userId);
            }
            System.out.println("[TenantConfig]" + JSONObject.toJSONString(tenantConfig));
            //------------------------------------------------------------------
            JSONObject res = new JSONObject();
            if (StringUtils.isEmpty(tenantId_Now)) {
                res.put("status", 998);
                res.put("message", "请选择租户信息");
                out = response.getWriter();
                out.append(res.toString());
                return false;
            } else if (StringUtils.isBlank(access_token)) {
                res.put("status", 998);
                res.put("message", "Token 不合法");
                out = response.getWriter();
                out.append(res.toString());
                return false;
            }
            //用友Token 验证
            boolean isAccessToken = myTokenService.isAccessToken(tenantId_Now, access_token);
            if (isAccessToken) {
                return true;
            }
            // 私有token方案放行
            else if (MyTool.checkToken(access_token, tenantId_Now)) {
                return true;
            }
            //默认禁止
            else {
                res.put("status", 998);
                res.put("message", "用友Token 不合法");
                out = response.getWriter();
                out.append(res.toString());
                return false;
            }
        } catch (Exception ex) {
            System.out.println("[HeaderInterceptor][GDGY-ERROR]" + ex.getMessage());
            logger.error("[HeaderInterceptor][GDGY-ERROR]" + ex.getMessage());
        }

        return super.preHandle(request, response, handler);
    }

}
